﻿using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WTAppletProjectHTTPS.Models;

namespace WTAppletProjectHTTPS.Controllers
{

    public class TestStationChangeMaterialConfirmationQueryController : ApiController
    {
        private static readonly Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        // POST api/<controller>
        public async Task<HttpResponseMessage> Post([FromBody] TestStationChangeMaterialConfirmationQuery TSCMCQ)
        {
            ReturnObjectQuery RO = new ReturnObjectQuery();
            if (TSCMCQ.PageNumber <= 0 || TSCMCQ.PageSize <= 0)
            {
                RO.Status = HttpStatusCode.BadRequest;
                RO.Message = "分页参数无效";
                RO.Data = null;
                Logger.Error("分页参数无效");
                return Request.CreateResponse(HttpStatusCode.BadRequest, RO);
            }

            try
            {
                using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString))
                {
                    await connection.OpenAsync();

                    var whereClause = "WHERE 1=1";
                    if (TSCMCQ.TSCMC_ID != 0)
                    {
                        whereClause += " AND TSCMCID=@ID";
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_OperatorName))
                    {
                        whereClause += " AND TSCMCOperatorName LIKE @OperatorName";
                    }
                    if (TSCMCQ.TSCMC_ConfirmationTime.HasValue)
                    {
                        whereClause += " AND TSCMCConfirmationTime = @ConfirmationTime";
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_LineParting))
                    {
                        whereClause += " AND TSCMCLineParting LIKE @LineParting";
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_ProductModel))
                    {
                        whereClause += " AND TSCMCProductModel LIKE @ProductModel";
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_ModuleModel))
                    {
                        whereClause += " AND TSCMCModuleModel LIKE @ModuleModel";
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_ModuleCorrectnessCheck))
                    {
                        whereClause += " AND TSCMCModuleCorrectnessCheck LIKE @ModuleCorrectnessCheck";
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_NonconformanceDescription))
                    {
                        whereClause += " AND TSCMCNonconformanceDescription LIKE @NonconformanceDescription";
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_NonconformanceImage))
                    {
                        whereClause += " AND TSCMCNonconformanceImage LIKE @NonconformanceImage";
                    }

                    var query = $@"
                        SELECT 
                            TSCMCID, TSCMCOperatorName, TSCMCConfirmationTime, TSCMCLineParting, TSCMCProductModel, 
                            TSCMCModuleModel, TSCMCModuleCorrectnessCheck, TSCMCNonconformanceDescription, TSCMCNonconformanceImage,TSCMCCreateCreator,TSCMCCreateTime,
                            COUNT(*) OVER() AS TotalCount
                        FROM 
                            (SELECT 
                                TSCMCID, TSCMCOperatorName, TSCMCConfirmationTime, TSCMCLineParting, TSCMCProductModel, 
                                TSCMCModuleModel, TSCMCModuleCorrectnessCheck, TSCMCNonconformanceDescription, TSCMCNonconformanceImage,TSCMCCreateCreator,TSCMCCreateTime,
                                ROW_NUMBER() OVER(ORDER BY TSCMCID) AS RowNum
                             FROM TestStationChangeMaterialConfirmation {whereClause}) AS Result
                        WHERE 
                            RowNum BETWEEN @StartRow AND @EndRow
                        ORDER BY RowNum";

                    int startRow = (TSCMCQ.PageNumber - 1) * TSCMCQ.PageSize + 1;
                    int endRow = TSCMCQ.PageNumber * TSCMCQ.PageSize;

                    var parameters = new List<SqlParameter>
                    {
                        new SqlParameter("@StartRow", SqlDbType.Int) { Value = startRow },
                        new SqlParameter("@EndRow", SqlDbType.Int) { Value = endRow }
                    };
                    if (TSCMCQ.TSCMC_ID != 0)
                    {
                        parameters.Add(new SqlParameter("@ID", SqlDbType.Int) { Value = TSCMCQ.TSCMC_ID });
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_OperatorName))
                    {
                        parameters.Add(new SqlParameter("@OperatorName", SqlDbType.NVarChar, 50) { Value = $"%{TSCMCQ.TSCMC_OperatorName}%" });
                    }
                    if (TSCMCQ.TSCMC_ConfirmationTime.HasValue)
                    {
                        parameters.Add(new SqlParameter("@ConfirmationTime", SqlDbType.DateTime) { Value = TSCMCQ.TSCMC_ConfirmationTime });
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_LineParting))
                    {
                        parameters.Add(new SqlParameter("@LineParting", SqlDbType.NVarChar, 50) { Value = $"%{TSCMCQ.TSCMC_LineParting}%" });
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_ProductModel))
                    {
                        parameters.Add(new SqlParameter("@ProductModel", SqlDbType.NVarChar, 50) { Value = $"%{TSCMCQ.TSCMC_ProductModel}%" });
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_ModuleModel))
                    {
                        parameters.Add(new SqlParameter("@ModuleModel", SqlDbType.NVarChar, 50) { Value = $"%{TSCMCQ.TSCMC_ModuleModel}%" });
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_ModuleCorrectnessCheck))
                    {
                        parameters.Add(new SqlParameter("@ModuleCorrectnessCheck", SqlDbType.NVarChar, 50) { Value = $"%{TSCMCQ.TSCMC_ModuleCorrectnessCheck}%" });
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_NonconformanceDescription))
                    {
                        parameters.Add(new SqlParameter("@NonconformanceDescription", SqlDbType.NVarChar, 100) { Value = $"%{TSCMCQ.TSCMC_NonconformanceDescription}%" });
                    }
                    if (!string.IsNullOrEmpty(TSCMCQ.TSCMC_NonconformanceImage))
                    {
                        parameters.Add(new SqlParameter("@NonconformanceImage", SqlDbType.NVarChar, 100) { Value = $"%{TSCMCQ.TSCMC_NonconformanceImage}%" });
                    }

                    using (var command = new SqlCommand(query, connection))
                    {
                        command.Parameters.AddRange(parameters.ToArray());
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            if (!reader.HasRows)
                            {
                                Logger.Warn("未找到记录");
                                RO.Status = HttpStatusCode.NotFound;
                                RO.Message = "未找到记录";
                                RO.Data = null;
                                return Request.CreateResponse(HttpStatusCode.NotFound, RO);
                            }

                            var products = new List<TestStationChangeMaterialConfirmation>();
                            int totalCount = 0;
                            while (await reader.ReadAsync())
                            {
                                if (totalCount == 0)
                                {
                                    totalCount = reader.GetInt32(reader.GetOrdinal("TotalCount"));
                                }

                                products.Add(new TestStationChangeMaterialConfirmation
                                {
                                    TSCMC_ID = reader.GetInt32(reader.GetOrdinal("TSCMCID")),
                                    TSCMC_OperatorName = reader.GetString(reader.GetOrdinal("TSCMCOperatorName")),
                                    TSCMC_ConfirmationTime = reader.GetDateTime(reader.GetOrdinal("TSCMCConfirmationTime")),
                                    TSCMC_LineParting = reader.GetString(reader.GetOrdinal("TSCMCLineParting")),
                                    TSCMC_ProductModel = reader.GetString(reader.GetOrdinal("TSCMCProductModel")),
                                    TSCMC_ModuleModel = reader.GetString(reader.GetOrdinal("TSCMCModuleModel")),
                                    TSCMC_ModuleCorrectnessCheck = reader.GetString(reader.GetOrdinal("TSCMCModuleCorrectnessCheck")),
                                    TSCMC_NonconformanceDescription = reader.GetString(reader.GetOrdinal("TSCMCNonconformanceDescription")),
                                    TSCMC_NonconformanceImage = reader.GetString(reader.GetOrdinal("TSCMCNonconformanceImage")),
                                    TSCMC_CreateCreator = reader.GetString(reader.GetOrdinal("TSCMCCreateCreator")),
                                    TSCMC_CreateTime = reader.GetDateTime(reader.GetOrdinal("TSCMCCreateTime"))
                                });
                            }

                            Logger.Info("查询成功");
                            RO.Status = HttpStatusCode.OK;
                            RO.Message = "OK";
                            RO.Data = products;
                            RO.TotalCount = totalCount;
                            RO.PageNumber = TSCMCQ.PageNumber;
                            RO.PageSize = TSCMCQ.PageSize;
                            return Request.CreateResponse(HttpStatusCode.OK, RO);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("查询失败: " + ex.Message);
                RO.Status = HttpStatusCode.InternalServerError;
                RO.Message = "Error: " + ex.Message;
                RO.Data = null;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, RO);
            }
        }
    }
}
